package com.sinosoft.sinopay.apiservice.allinpay.service;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.springframework.stereotype.Service;

import com.allinpay.XmlTools;
import com.sinosoft.sinocloud.platform.base.SinoBaseException;
import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.exception.biz.SinoBizException;
import com.sinosoft.sinocloud.platform.common.exception.system.SinoSystemException;
import com.sinosoft.sinocloud.platform.common.util.XStreamComponent;
import com.sinosoft.sinopay.api.pay.dto.AllinpayQryDetailsRespDTO;
import com.sinosoft.sinopay.api.pay.dto.AllinpayQryReqDTO;
import com.sinosoft.sinopay.api.pay.dto.AllinpayQryRespDTO;
import com.sinosoft.sinopay.api.pay.service.InteraAllinPayQryApiService;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryList;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryReq;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryReqHead;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryReqXml;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryResp;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryRespHead;
import com.sinosoft.sinopay.apiservice.allinpay.dto.PayTradeResultQueryRespXml;
import com.sinosoft.sinopay.apiservice.allinpay.util.PropertiesUtils;
/**  
 * 【通联交易结果查询  实现】 
 * @author dengcanyang
 * @date 2017年01月10日 下午18:47:28  
 * @version V1.0    
 */
@Service("InterPayByPayTradeQuery")
public class PayTradeResultQueryServiceImpl extends SinoBaseService implements InteraAllinPayQryApiService{
    @Override
	public AllinpayQryRespDTO payRequest(AllinpayQryReqDTO tAllinpayReqDTO)
			throws SinoBaseException, SinoSystemException {
        //返回信息 给交易服务
        AllinpayQryRespDTO tAllinpayQryRespList = new AllinpayQryRespDTO();  //返回封装体定义
		try{
		    PayTradeResultQueryReqXml  requestXml = new  PayTradeResultQueryReqXml();
			PayTradeResultQueryReqHead reqHeadInfo = new PayTradeResultQueryReqHead();
            String tPath="/config/allinpayConfig.properties";
            Properties properties = PropertiesUtils.readProperties(tPath);
            reqHeadInfo.setDATA_TYPE(properties.getProperty("DATA_TYPE"));    //报文头 数据格式 
            reqHeadInfo.setTRX_CODE("200004");      //交易代码 properties.getProperty("TRX_CODE")
            reqHeadInfo.setUSER_NAME(properties.getProperty("USER_NAME"));    //用户名
            reqHeadInfo.setUSER_PASS(properties.getProperty("USER_PASS"));    //用户密码
            reqHeadInfo.setVERSION(properties.getProperty("VERSION"));  //版本
            reqHeadInfo.setSIGNED_MSG("");   //签名信息
            requestXml.setINFO(reqHeadInfo);
            PayTradeResultQueryReq reqTransSum = new PayTradeResultQueryReq(); //报文体
            reqTransSum.setMERCHANT_ID(tAllinpayReqDTO.getMERCHANT_ID());
            //提交时间 为当前系统时间
            reqTransSum.setSTATUS(tAllinpayReqDTO.getSTATUS());
            reqTransSum.setTYPE(tAllinpayReqDTO.getTYPE());
            reqTransSum.setQUERY_SN(tAllinpayReqDTO.getQUERY_SN());
            reqTransSum.setSTARTTIME(tAllinpayReqDTO.getSTART_DAY());
            reqTransSum.setENDTIME(tAllinpayReqDTO.getEND_DAY());  //
            requestXml.setQTRANSREQ(reqTransSum);
            requestXml.setQTRANSREQ(reqTransSum);
            //封装请求的xml
            XStreamComponent xstream = new XStreamComponent();
            xstream.processAnnotations(new Class[] { PayTradeResultQueryReqXml.class,PayTradeResultQueryReqHead.class,PayTradeResultQueryReq.class,
                    PayTradeResultQueryRespXml.class,PayTradeResultQueryRespHead.class,PayTradeResultQueryList.class,PayTradeResultQueryResp.class});
            String reqXml = properties.getProperty("Package_Header")+xstream.toXML(requestXml).replace("__", "_");
            System.out.println("请求报文：\n"+reqXml);
            String signData = this.signMsg(reqXml);  
            String url = properties.getProperty("SERVER_URL");
            boolean flag =false;
            String strResp = sendXml(signData,url,flag);
            //解析返回报文  
            PayTradeResultQueryRespXml response = (PayTradeResultQueryRespXml) xstream.fromXML(strResp);
            String returnCode = response.getINFO().getRET_CODE(); //头部返回编码 
            if(returnCode!=null && !returnCode.equals("0000")){  //失败返回 信息处理  ，不成功就继续查询, 每隔多久查一次并重复请求。
            	/*payInfoReturn.setReturnCode(returnCode);
                payInfoReturn.setReturnMsg(response.getINFO().getERR_MSG());  //失败信息 */
                tAllinpayQryRespList.setRET_CODE(returnCode);  //处理结果条数
                tAllinpayQryRespList.setERR_MSG("查询交易信息失败，请重新查询");
            }else{  //成功 返回信息 成功就更新状态
                for (int i = 0; i < response.getQTRANSRSP().getQTDETAIL().size(); i++) {  //封装返回信息
                    tAllinpayQryRespList.setRET_CODE(returnCode);  //处理结果编码
                    tAllinpayQryRespList.setERR_MSG("当前共查询出"+response.getQTRANSRSP().getQTDETAIL().size()+"条数据信息，详细描述信息如下：");
                    List<AllinpayQryDetailsRespDTO> tAllinpayQryDetailsRespList = new ArrayList<AllinpayQryDetailsRespDTO>();
                     if (!"".equals(response.getQTRANSRSP().getQTDETAIL().get(i).getBATCHID())||null!=response.getQTRANSRSP().getQTDETAIL().get(i).getBATCHID()) {
                         AllinpayQryDetailsRespDTO tAllinpayQryRespDTO = new AllinpayQryDetailsRespDTO();
                        tAllinpayQryRespDTO.setBATCHID(response.getQTRANSRSP().getQTDETAIL().get(i).getBATCHID());
                        tAllinpayQryRespDTO.setSN(response.getQTRANSRSP().getQTDETAIL().get(i).getSN());
                        tAllinpayQryRespDTO.setTRXDIR(response.getQTRANSRSP().getQTDETAIL().get(i).getTRXDIR());
                        tAllinpayQryRespDTO.setSETTDAY(response.getQTRANSRSP().getQTDETAIL().get(i).getSETTDAY());
                        tAllinpayQryRespDTO.setFINTIME(response.getQTRANSRSP().getQTDETAIL().get(i).getFINTIME());
                        tAllinpayQryRespDTO.setSUBMITTIME(response.getQTRANSRSP().getQTDETAIL().get(i).getSUBMITTIME());
                        tAllinpayQryRespDTO.setACCOUNT_NO(response.getQTRANSRSP().getQTDETAIL().get(i).getACCOUNT_NO());
                        tAllinpayQryRespDTO.setACCOUNT_NAME(response.getQTRANSRSP().getQTDETAIL().get(i).getACCOUNT_NAME());
                        tAllinpayQryRespDTO.setAMOUNT(response.getQTRANSRSP().getQTDETAIL().get(i).getAMOUNT());
                        tAllinpayQryRespDTO.setRET_CODE(response.getQTRANSRSP().getQTDETAIL().get(i).getRET_CODE());
                        tAllinpayQryRespDTO.setERR_MSG(response.getQTRANSRSP().getQTDETAIL().get(i).getERR_MSG());
                        tAllinpayQryDetailsRespList.add(tAllinpayQryRespDTO);
                    }
                    tAllinpayQryRespList.setAllinpayQryDetailsList(tAllinpayQryDetailsRespList);
                }
            }
		}
		catch(Exception ex){
			ex.printStackTrace();
			/*payInfoReturn.setReturnCode("FAIL");
			payInfoReturn.setReturnMsg("异常信息："+ex.getMessage());*/
			tAllinpayQryRespList.setRET_CODE("FAIL");  //处理结果条数
            tAllinpayQryRespList.setERR_MSG("查询处理异常，异常信息为："+ex.getMessage());
		}
		return tAllinpayQryRespList;
	}
    /**
     * 
     * 发送报文
     * @param xml
     * @param url
     * @param isFront
     * @return resp 响应报文
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
	public String sendXml(String xml,String url,boolean isFront) throws UnsupportedEncodingException, Exception{
		String resp="";
		try {
			resp=XmlTools.send(url,new String(xml.getBytes(),"UTF-8"));
		} catch (SinoBaseException ee) {
            throw new SinoBizException(ee.getMessage());
        }catch (Exception e) {
			//e.printStackTrace();
			throw new SinoBizException("请求发送异常："+e.getMessage());
		}
		System.out.println("======================响应内容======================\n"+resp) ;
		String rootPath = this.getClass().getResource("").getPath().toString();
        String pathPfx = rootPath + "config/allinpay-pds.cer";
		/*File directory = new File("");
        String pathPfx = "\\"+directory.getAbsolutePath()+"\\resources\\config\\allinpay-pds.cer";*/
        boolean flag= false;
        try {
        	flag= this.verifyMsg(resp, pathPfx,isFront);  //暂时不做签验
		} catch (Exception e) { 
			e.printStackTrace();
			throw new SinoBizException("返回报文秘钥签验异常："+e.getMessage());
		}
		if(flag){
			System.out.println("响应内容验证通过");
		}else{
			System.out.println("响应内容验证不通过");
		}
		return resp;
	}
	/**
	 * 验证签名
	 * @param msg
	 * @return
	 *日期：Sep 9, 2012
	 * @throws Exception 
	 */
	public boolean verifyMsg(String msg,String cer,boolean isFront) throws Exception{
	    boolean flag=XmlTools.verifySign(msg, cer, false,isFront);
		System.out.println("验签结果["+flag+"]") ;
		return flag;
	}
	/**
	 * 数据签名
	 * @param strData
	 * @return
	 * @throws CryptException
	 */
	public String signMsg(String strData) throws Exception {
        System.out.println("-----star---获取数据签名-------");
        String rootPath = this.getClass().getResource("").getPath().toString();
        String pathPfx = rootPath + "config/20060400000044502.p12";
       /* File directory = new File("");
        String pathPfx = "\\"+directory.getAbsolutePath()+"\\resources\\config\\20060400000044502.p12";*/
        String pass="111111";
        String xml= signRSAMsg(strData,pathPfx,pass);
        System.out.println("发送报文信息:\n"+xml);
        return  xml;
    }
	/**
	 * 报文签名 加密
	 * @param msg
	 * @return
	 * @throws Exception 
	 */
	public String signRSAMsg(String xml,String pathPfx,String pass) throws Exception{
	    try {
            xml=XmlTools.signMsg(xml, pathPfx,pass, false);
        } catch (Exception e) {
            throw new SinoBizException("请求报文秘钥签验异常："+e.getMessage());
        }
		return xml;
	}
}
